Introduction to Python: Basic Python

Authors:

Tahmidul Azom Sany (tsany@gmu.edu)

Python is useful in climate science for data analysis, modeling, machine learning, data visualization, and data processing tasks. Its ease of use, extensive libraries, and robust scientific computing capabilities make it a versatile tool for climate scientists to analyze, model, visualize, and communicate climate data and research findings. In this tutorial we will explore some of the basic features of python which will be useful in climate data analysis.

Prerequisite: It is recommended for users to have a basic understanding of the Python programming language before proceeding with this tutorial. This tutorial covers some of the fundamental features (but not all) of Python. Therefore, if you are new to programming, we suggest starting with the following resources:


**Resources for learning Python**

Syllabus

1. System Setup
2. Hello World
3. Drawing a shape
4. Variables and Data Type
5. Strings
6. Numbers
7. Input from user
8. Conditional statement
9. Building a basic calculator
10. Function
11. Loops
12. Try and Except
13. Modules and packages

1. System Setup

Let's start with our system setup. Open https://colab.research.google.com/and open File ->New Notebook. That's all you need to start with Python. No prior installation requried into your local environment.

2. Hello World

In [ ]:
print("Hello World") # For printing a simple text
Hello World
In [ ]:
friend = 'James'
print(friend + " is Paul's friend")  # Approach 01
print(f"{friend} is Paul's friend") # Approach 02 # Find the problem here
print(friend, "is Paul's friend")  # Approach 03
James is Paul's friend
James is Paul's friend
James is Paul's friend

3. Drawing a shape

You can draw any shape you want with Python.

In [ ]:
print("       /|")
print("      / |")
print("     /  |")
print("    /   |")
print("   /    |")
print("  /_____|")
       /|
      / |
     /  |
    /   |
   /    |
  /_____|
In [ ]:
print("       O     ")
print("      /|\__#=== --------------------")
print("     / |     ")
print("      /|\   ")
print("     / | \   ")
       O     
      /|\__#=== --------------------
     / |     
      /|\   
     / | \   

4. Variables and Data type

In [ ]:
# Variable Naming Rules and Assigning Variable

#Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

#Illegal variable names:
# 2myvar = "John"
# my-var = "John"
# my var = "John"
In [ ]:
# Accessing Variable
myvar
Out[ ]:
'John'
In [ ]:
# Multiple assignment
a, b = 2,3
sum = a+b
sum
Out[ ]:
5

Task: Get a idea of

  • Local Variable
  • Gloabl Variable

5. Strings

In [ ]:
x = "Hello! This is a text here"
y = 200
type(x)
# What type is the y variable?
Out[ ]:
str
In [ ]:
a, b = "2", "3"
sum = a+b
sum
Out[ ]:
'23'
In [ ]:
# String Concat
x = "Omi"
y = "Loves"
z = "Rain"
print(x + y + z)
OmiLovesRain
In [ ]:
name = 'Cristiano Ronaldo'
age = '37'
print( name + ' is the best player in the world.')
print("He is " + age + " Years old")
print("But he doesn't look like "+ age +" Years old")
Cristiano Ronaldo is the best player in the world.
He is 37 Years old
But he doesn't look like 37 Years old
In [ ]:
print("This is first line. \nThis is second line")
This is first line. 
This is second line
In [ ]:
phrase = "Ahmed Al Imtiaz" # Ahmed Al Imtiaz is my friend name, You can add your full name Here

print(phrase.lower())
print(phrase.upper())
print(phrase.isupper())
print(phrase.islower())
print(phrase.upper().isupper())
ahmed al imtiaz
AHMED AL IMTIAZ
False
False
True
In [ ]:
# Operations
length = len(phrase) #to print the length of
first_index = phrase[0] #index start with 0
fourth_index = phrase[3]

# Finding an index
phrase.index("z")
phrase.index("tiaz")
phrase.replace("Imtiaz","Omi")
Out[ ]:
'Ahmed Al Omi'

6. Numbers

In [ ]:
# Finding type
a = 100
b = 10.22
c = True
d = [0,1,2,3,4]

type(a)
type(b)
type(c)
type(d)
Out[ ]:
list
In [ ]:
# Basic Calculations

print(3+2)
print(10%3) #finding a remainder
print(40/2) #division always returns a flaot
5
1
20.0
In [ ]:
# Converting number into string

num = 55
num_string = str(num)
type(num_string)
Out[ ]:
str
In [ ]:
# Operation

num = -2
absolute_value = abs(num) #returns absolute value
power_num = pow(4,2) #returns power 4^2
max_num = max(4,5,6,1,2,3)
min_num = min(1,3,2,5,7,2,3)
round_num = round(5.3)
In [ ]:
# math package

from math import *
a = floor(3.4)
b = ceil(3.4)

square_root = sqrt(16)
exponential = exp(10)
ln_value = log(2) # Natural Logarithm (Ln)
log_value = log10(2) # Base-10 Logarithm (Log)

print(ln_value) # Print other values
0.6931471805599453

7. Input from user

In [ ]:
Name = input("Enter your name: ")
Age = int(input("Enter your age: "))

# print("Welcome "+ Name + "! You are " + Age+ " years old" )
Enter your name: John
Enter your age: 12

8. Conditional Statement

In [ ]:
"""
I woke up
If I am hungry
    I eat food


Going to university
If it is raining
    I will bring an umbrella
otherwise
    I will not bring an umbrella
"""
In [ ]:
# Structure

"""
if condition:
____exicute this line
else:
____this line"""
In [ ]:
# Basic If Statement

is_male = False #try with False
is_tall = True

# if is_male or is_tall:
#     print("You are a male or a tall or both")

if is_male and is_tall:
    print("You are a tall male")

elif is_male and not(is_tall):
    print("You are a short male")

elif not(is_male) and is_tall:
    print("You are a tall but not a male")

else:
    print("You are neither male nor tall")
You are a tall but not a male
In [ ]:
# Comparison
a = 2
b = 3

if a>b:
    print("a is bigger")
if a==b:
    print("a is equal to b")
else:
    print("b is bigger")
b is bigger

9. Building a basic calculator

In [ ]:
num1 = float(input("Enter first number: "))
op = input("Enter operation: ")
num2 = float(input("Enter second number: "))

if op == '+':
    print(num1+num2)

elif op == '-':
    print(num1-num2)

elif op == '*':
    print(num1*num2)

elif op == '/':
    print(num1/num2)

else:
    print("Invalid Operation! ")
Enter first number: 3
Enter operation: +
Enter second number: 3
6.0

Task: Try to answer these two question.

- Why didn't we use int?
- Why did we we use float?

10. Functions

In [ ]:
# Structure
def function_name(variables):  #could be multiple variable
    statement
In [ ]:
def my_function():
    print("Function is called")

my_function()
Function is called
In [ ]:
def best_player(name):
    print(f"{name} is the best player.")

best_player("Cristiano Ronaldo")
Cristiano Ronaldo is the best player.
In [ ]:
def sumation(a,b,c):
    print(a+b+c)

sumation(1,2,3)
6

11. Loops

In [ ]:
i = 1
while i<10:
    print(i)
    i = i+1 # Approach 01
#   i += 1  # Approach 02
1
2
3
4
5
6
7
8
9

For loop

In [ ]:
for i, letter in enumerate("BD Climate"):
    print(i, letter)
0 B
1 D
2  
3 C
4 l
5 i
6 m
7 a
8 t
9 e
In [ ]:
for number in range(10):
    print(number) #why didn't it print 10
0
1
2
3
4
5
6
7
8
9
In [ ]:
for number in range(3, 10, 3):
    print(number)

# task is to get the sum of every odd number from 1 to 33(inclusive)
3
6
9
In [ ]:
student = ['Omi', 'Imtiaz', 'Tuaha']

for i in range(len(student)):
    print(student[i])
Omi
Imtiaz
Tuaha
In [ ]:
for index in range(5):
    if index==0:
        print("First iteration")
    else:
        print("Not First")
First iteration
Not First
Not First
Not First
Not First
In [ ]:
# Nested loop
color = ["Red", "Black", "Blue"]
car = ["BMW", "Marcedes", "Toyota"]

for value in color:
    for another_value in car:
        print(value, another_value)
Red BMW
Red Marcedes
Red Toyota
Black BMW
Black Marcedes
Black Toyota
Blue BMW
Blue Marcedes
Blue Toyota
In [ ]:
# print(3**2)
# we need to do this in loopic way

def to_the_power(base_number, power):
    result = 1
    for number in range(power):
        result = result * base_number
    return result
print(to_the_power(2,3))
8
In [ ]:
# 2D list

number_matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
    [0]
]

number_matrix[0][2]
# task is to make a 1D list from the above list.
# 1D list looks like [1,2,3.....0]
Out[ ]:
3

12. Try and except

In [ ]:
try:
    num = int(input("Enter a number: "))
    print(num)
except:
    print("Invalid Number")
Enter a number: 33
33

13. Modules and packages

In the next chapter we will deal with NumPy, Pandas and Matplotlib.